package com.java110.mall.goods.bmo.product.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.java110.core.annotation.Java110Transactional;
import com.java110.core.factory.GenerateCodeFactory;
import com.java110.dto.file.FileDto;
import com.java110.dto.file.FileRelDto;
import com.java110.dto.housekeeping.HousekeepingServDto;
import com.java110.dto.inoutOrder.InoutOrderDto;
import com.java110.dto.product.ProductCategoryDto;
import com.java110.dto.product.ProductSpecDto;
import com.java110.dto.shop.ShopHouseDto;
import com.java110.dto.user.UserDto;
import com.java110.mall.goods.bmo.product.ISaveProductBMO;
import com.java110.intf.cart.IInoutOrderInnerServiceSMO;
import com.java110.intf.cart.IInoutOrderProductInnerServiceSMO;
import com.java110.intf.system.IFileInnerServiceSMO;
import com.java110.intf.system.IFileRelInnerServiceSMO;
import com.java110.intf.goods.*;
import com.java110.intf.shop.IShopHouseInnerServiceSMO;
import com.java110.intf.user.IUserV1InnerServiceSMO;
import com.java110.po.file.FileRelPo;
import com.java110.po.inoutOrder.InoutOrderPo;
import com.java110.po.inoutOrder.InoutOrderProductPo;
import com.java110.po.product.ProductPo;
import com.java110.po.product.ProductDetailPo;
import com.java110.po.product.ProductServKeywordPo;
import com.java110.po.product.ProductSpecValuePo;
import com.java110.po.shop.ShopDistributionModePo;
import com.java110.utils.util.Assert;
import com.java110.utils.util.StringUtil;
import com.java110.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Service("saveProductBMOImpl")
public class SaveProductBMOImpl implements ISaveProductBMO {

    @Autowired
    private IProductInnerServiceSMO productInnerServiceSMOImpl;

    @Autowired
    private IFileInnerServiceSMO fileInnerServiceSMOImpl;

    @Autowired
    private IFileRelInnerServiceSMO fileRelInnerServiceSMOImpl;

    @Autowired
    private IProductSpecValueInnerServiceSMO productSpecValueInnerServiceSMOImpl;

    @Autowired
    private IProductDetailInnerServiceSMO productDetailInnerServiceSMOImpl;

    @Autowired
    private IProductServKeywordInnerServiceSMO productServKeywordInnerServiceSMOImpl;

    @Autowired
    private IInoutOrderProductInnerServiceSMO iInoutOrderProductInnerServiceSMOImpl;

    @Autowired
    private IInoutOrderInnerServiceSMO inoutOrderInnerServiceSMOImpl;

    @Autowired
    private IUserV1InnerServiceSMO userInnerServiceSMOImpl;

    @Autowired
    private IProductCategoryInnerServiceSMO productCategoryInnerServiceSMOImpl;

    @Autowired
    private IShopHouseInnerServiceSMO shopHouseInnerServiceSMOImpl;

    @Autowired
    private IProductSpecInnerServiceSMO productSpecValuePosImpl;
    @Autowired
    private IShopDistributionModeInnerServiceSMO shopDistributionModeInnerServiceSMOImpl;

    /**
     * 添加小区信息
     *
     * @param productPo
     * @return 订单服务能够接受的报文
     */
    @Java110Transactional
    public ResponseEntity<String> save(ProductPo productPo, String coverPhoto, JSONArray carouselFigurePhoto,
                                       List<ProductSpecValuePo> productSpecValuePos, ProductDetailPo productDetailPo, String userId, ShopDistributionModePo shopDistributionModePo) {
        productPo.setProductId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_productId));
        int flag = productInnerServiceSMOImpl.saveProduct(productPo);

//        if (!"-1".equals(shopDistributionModePo.getModeId())) {
//            //处理商品与配送方式关系
//            shopDistributionModePo.setShopModeId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_shopModeId));
//            shopDistributionModePo.setProductId(productPo.getProductId());
//            shopDistributionModePo.setProdName(productPo.getProdName());
//            flag = shopDistributionModeInnerServiceSMOImpl.saveShopDistributionMode(shopDistributionModePo);
//            if (flag < 1) {
//                return ResultVo.createResponseEntity(ResultVo.CODE_ERROR, "保存商品与配送方式关系失败");
//            }
//        }

        //关键词处理
        doSavakeywords(productPo);
        if (flag < 1) {
            return ResultVo.createResponseEntity(ResultVo.CODE_ERROR, "保存失败");
        }
        //保存商品封面
        doSavaRentingFile(coverPhoto, productPo, FileRelDto.REL_TYPE_CD_GOODS_COVER);
        for (int carouselIndex = 0; carouselIndex < carouselFigurePhoto.size(); carouselIndex++) {
            doSavaRentingFile(carouselFigurePhoto.getString(carouselIndex), productPo, FileRelDto.REL_TYPE_CD_GOODS_CAROUSEL_FIGURE);
        }
        for (ProductSpecValuePo productSpecValuePo : productSpecValuePos) {
            productSpecValuePo.setStoreId(productPo.getStoreId());
            productSpecValuePo.setProductId(productPo.getProductId());
            productSpecValuePo.setValueId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_valueId));
            if(StringUtil.isEmpty(productSpecValuePo.getDeduction())){
                productSpecValuePo.setDeduction("0.00");
            }
            flag = productSpecValueInnerServiceSMOImpl.saveProductSpecValue(productSpecValuePo);
            if (flag < 1) {
                throw new IllegalArgumentException("保存规格失败");
            }
        }
        productDetailPo.setProductId(productPo.getProductId());
        productDetailPo.setDetailId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_detailId));
        flag = productDetailInnerServiceSMOImpl.saveProductDetail(productDetailPo);
        if (flag < 1) {
            throw new IllegalArgumentException("保存规格失败");
        }
        InoutOrderPo inoutOrderPo = new InoutOrderPo();
        inoutOrderPo.setOrderId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_orderId));
        inoutOrderPo.setShopId(productPo.getShopId());
        inoutOrderPo.setState(InoutOrderDto.STATE_C);
        inoutOrderPo.setOrderType(InoutOrderDto.ORDER_TYPE_IN);
        inoutOrderPo.setPersonId(userId);
        UserDto userDto = new UserDto();
        userDto.setUserId(userId);
        List<UserDto> userDtos = userInnerServiceSMOImpl.queryUsers(userDto);

        Assert.listOnlyOne(userDtos, "未包含用户信息");
        inoutOrderPo.setPersonName(userDtos.get(0).getName());
        inoutOrderPo.setRemark("添加商品初始化入库");
        //开始保存 inoutOrderProduct
        InoutOrderProductPo inoutOrderProductPo = null;
        List<InoutOrderProductPo> inoutOrderProductPos = new ArrayList<>();

        for (ProductSpecValuePo productSpecValuePo : productSpecValuePos) {
            if (productSpecValuePo.getStock() != null && Integer.parseInt(productSpecValuePo.getStock()) > 0) {//初始库存大于0
                inoutOrderProductPo = new InoutOrderProductPo();
                inoutOrderProductPo.setRsId("111111");
                inoutOrderProductPo.setSupplierName("添加商品时统一入库");
                inoutOrderProductPo.setPrice(productSpecValuePo.getCostPrice());
                inoutOrderProductPo.setProdCount(productSpecValuePo.getStock());
                BigDecimal price = new BigDecimal(Double.parseDouble(inoutOrderProductPo.getPrice()));
                price = price.multiply(new BigDecimal(Double.parseDouble(inoutOrderProductPo.getProdCount()))).setScale(2, BigDecimal.ROUND_HALF_EVEN);
                inoutOrderProductPo.setAmount(price.doubleValue() + "");
                inoutOrderProductPo.setItemId(GenerateCodeFactory.getGeneratorId("11"));
                inoutOrderProductPo.setOrderId(inoutOrderPo.getOrderId());
                inoutOrderProductPo.setProductId(productPo.getProductId());
                inoutOrderProductPo.setProdName(productPo.getProdName());
                inoutOrderProductPo.setShopId(inoutOrderPo.getShopId());
                inoutOrderProductPo.setState(InoutOrderDto.STATE_W);
                inoutOrderProductPo.setValueId(productSpecValuePo.getValueId());
                inoutOrderProductPo.setRemark("添加商品时统一入库");
                inoutOrderProductPo.setSpecName(productSpecValuePo.getSpecName());
                inoutOrderProductPos.add(inoutOrderProductPo);
            }
        }
        flag = iInoutOrderProductInnerServiceSMOImpl.saveInoutOrderProducts(inoutOrderProductPos);
        if (flag < 1) {
            throw new IllegalArgumentException("提交失败");
        }
        flag = inoutOrderInnerServiceSMOImpl.saveInoutOrder(inoutOrderPo);
        if (flag < 1) {
            throw new IllegalArgumentException("提交失败");
        }
        return ResultVo.createResponseEntity(ResultVo.CODE_OK, "保存成功");
    }

    @Override
    public ResponseEntity<String> importProducts(JSONObject reqJson, String storeId, String userId) {
        Assert.hasKeyAndValue(reqJson, "shopId", "未包含商铺信息");
        if (!reqJson.containsKey("products")) {
            throw new IllegalArgumentException("未包含商品信息");
        }

        JSONArray products = reqJson.getJSONArray("products");
        if (products == null || products.size() < 1) {
            throw new IllegalArgumentException("未包含商品信息");
        }
        for (int productIndex = 0; productIndex < products.size(); productIndex++) {
            doImportProducts(reqJson, products.getJSONObject(productIndex), storeId, userId);
        }

        return ResultVo.success();
    }


    private void doImportProducts(JSONObject reqJson, JSONObject jsonObject, String storeId, String userId) {
        ProductCategoryDto productCategoryDto = new ProductCategoryDto();
        productCategoryDto.setShopId(reqJson.getString("shopId"));
        productCategoryDto.setCategoryName(jsonObject.getString("categoryName"));
        List<ProductCategoryDto> productCategoryDtos = productCategoryInnerServiceSMOImpl.queryProductCategorys(productCategoryDto);

        Assert.listOnlyOne(productCategoryDtos, "目录不存在");

        ShopHouseDto shopHouseDto = new ShopHouseDto();
        shopHouseDto.setShopId(reqJson.getString("shopId"));
        shopHouseDto.setShName(jsonObject.getString("categoryName"));
        List<ShopHouseDto> shopHouseDtos = shopHouseInnerServiceSMOImpl.queryShopHouses(shopHouseDto);
        Assert.listOnlyOne(shopHouseDtos, "仓库不存在");

        ProductPo productPo = new ProductPo();
        productPo.setProductId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_productId));
        productPo.setBarCode("1");
        productPo.setCategoryId(productCategoryDtos.get(0).getCategoryId());
        productPo.setKeyword(jsonObject.getString("keyword"));
        productPo.setIsPostage("2");
        productPo.setProdDesc("系统导入");
        productPo.setProdName(jsonObject.getString("prodName"));
        productPo.setShId(shopHouseDtos.get(0).getShId());
        productPo.setShName(shopHouseDtos.get(0).getShName());
        productPo.setSort(jsonObject.getString("productId"));
        productPo.setShopId(reqJson.getString("shopId"));
        productPo.setState("上架".equals(jsonObject.getString("stateName")) ? "2002" : "1001");
        productPo.setStoreId(storeId);
        productPo.setUnitName(reqJson.getString("unitName"));
        productPo.setWarnStock(reqJson.getString("warnStock"));
        int flag = productInnerServiceSMOImpl.saveProduct(productPo);
        //关键词处理
        doSavakeywords(productPo);
        if (flag < 1) {
            throw new IllegalArgumentException("保存失败");
        }

        JSONArray importProductExtands = jsonObject.getJSONArray("importProductExtands");

        ProductSpecValuePo productSpecValuePo = null;
        JSONObject importProduct = null;
        List<ProductSpecValuePo> productSpecValuePos = new ArrayList<>();
        for (int specIndex = 0; specIndex < importProductExtands.size(); specIndex++) {
            importProduct = importProductExtands.getJSONObject(specIndex);
            productSpecValuePo = new ProductSpecValuePo();
            productSpecValuePo.setWillExpire("0");
            productSpecValuePo.setAttrition("0");
            productSpecValuePo.setValueId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_valueId));
            productSpecValuePo.setProductId(productPo.getProductId());
            productSpecValuePo.setStock(importProduct.getString("stock"));
            productSpecValuePo.setSales(importProduct.getString("sales"));
            productSpecValuePo.setShopId(reqJson.getString("shopId"));
            productSpecValuePo.setStoreId(storeId);
            productSpecValuePo.setBarCode(importProduct.getString("barCode"));

            productSpecValuePo.setCostPrice(importProduct.getString("costPrice"));
            productSpecValuePo.setIsDefault("F");
            productSpecValuePo.setMinusStock("1");
            productSpecValuePo.setOtPrice(importProduct.getString("otPrice"));
            productSpecValuePo.setPrice(importProduct.getString("price"));
            productSpecValuePo.setVipPrice(importProduct.getString("vipPrice"));
            productSpecValuePo.setSpecId(importProduct.getString("specId"));
            ProductSpecDto productSpecDto = new ProductSpecDto();
            productSpecDto.setSpecId(importProduct.getString("specId"));
            productSpecDto.setShopId(reqJson.getString("shopId"));
            List<ProductSpecDto> productSpecDtos = productSpecValuePosImpl.queryProductSpecs(productSpecDto);
            Assert.listOnlyOne(productSpecDtos, "规格不存在");
            productSpecValuePo.setSpecName(productSpecDtos.get(0).getSpecName());
            flag = productSpecValueInnerServiceSMOImpl.saveProductSpecValue(productSpecValuePo);
            if (flag < 1) {
                throw new IllegalArgumentException("保存规格失败");
            }

            productSpecValuePos.add(productSpecValuePo);
        }

        InoutOrderPo inoutOrderPo = new InoutOrderPo();
        inoutOrderPo.setOrderId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_orderId));
        inoutOrderPo.setShopId(productPo.getShopId());
        inoutOrderPo.setState(InoutOrderDto.STATE_C);
        inoutOrderPo.setOrderType(InoutOrderDto.ORDER_TYPE_IN);
        inoutOrderPo.setPersonId(userId);
        UserDto userDto = new UserDto();
        userDto.setUserId(userId);
        List<UserDto> userDtos = userInnerServiceSMOImpl.queryUsers(userDto);

        Assert.listOnlyOne(userDtos, "未包含用户信息");
        inoutOrderPo.setPersonName(userDtos.get(0).getName());
        inoutOrderPo.setRemark("添加商品初始化入库");
        //开始保存 inoutOrderProduct
        InoutOrderProductPo inoutOrderProductPo = null;
        List<InoutOrderProductPo> inoutOrderProductPos = new ArrayList<>();

        for (ProductSpecValuePo tmpProductSpecValuePo : productSpecValuePos) {
            if (productSpecValuePo.getStock() != null && Integer.parseInt(tmpProductSpecValuePo.getStock()) > 0) {//初始库存大于0
                inoutOrderProductPo = new InoutOrderProductPo();
                inoutOrderProductPo.setRsId("111111");
                inoutOrderProductPo.setSupplierName("添加商品时统一入库");
                inoutOrderProductPo.setPrice(tmpProductSpecValuePo.getCostPrice());
                inoutOrderProductPo.setProdCount(tmpProductSpecValuePo.getStock());
                BigDecimal price = new BigDecimal(Double.parseDouble(inoutOrderProductPo.getPrice()));
                price = price.multiply(new BigDecimal(Double.parseDouble(inoutOrderProductPo.getProdCount()))).setScale(2, BigDecimal.ROUND_HALF_EVEN);
                inoutOrderProductPo.setAmount(price.doubleValue() + "");
                inoutOrderProductPo.setItemId(GenerateCodeFactory.getGeneratorId("11"));
                inoutOrderProductPo.setOrderId(inoutOrderPo.getOrderId());
                inoutOrderProductPo.setProductId(productPo.getProductId());
                inoutOrderProductPo.setProdName(productPo.getProdName());
                inoutOrderProductPo.setShopId(inoutOrderPo.getShopId());
                inoutOrderProductPo.setState(InoutOrderDto.STATE_W);
                inoutOrderProductPo.setValueId(tmpProductSpecValuePo.getValueId());
                inoutOrderProductPo.setRemark("添加商品时统一入库");
                inoutOrderProductPo.setSpecName(tmpProductSpecValuePo.getSpecName());
                inoutOrderProductPos.add(inoutOrderProductPo);
            }
        }
        flag = iInoutOrderProductInnerServiceSMOImpl.saveInoutOrderProducts(inoutOrderProductPos);
        if (flag < 1) {
            throw new IllegalArgumentException("提交失败");
        }
        flag = inoutOrderInnerServiceSMOImpl.saveInoutOrder(inoutOrderPo);
        if (flag < 1) {
            throw new IllegalArgumentException("提交失败");
        }
    }

    /**
     * 保存关键词
     *
     * @param productPo
     */
    private void doSavakeywords(ProductPo productPo) {
        String[] keywor = productPo.getKeyword().replaceAll("；", ";").split(";");
        for (String keyword : keywor) {
            ProductServKeywordPo servKeywordPo = new ProductServKeywordPo();
            servKeywordPo.setKeywordId(GenerateCodeFactory.getGeneratorId("11"));
            servKeywordPo.setKeywordName(keyword.trim());
            servKeywordPo.setKeywordType(HousekeepingServDto.KEYWORD_PROD_TYPE_CD);
            servKeywordPo.setObjId(productPo.getProductId());
            servKeywordPo.setShopId(productPo.getShopId());
            int save = productServKeywordInnerServiceSMOImpl.saveProductServKeyword(servKeywordPo);
            if (save < 1) {
                throw new IllegalArgumentException("商品关键字保存失败");
            }
        }
    }

    /**
     * 保存房屋租赁 图片
     *
     * @param photo
     * @param productPo
     */
    private void doSavaRentingFile(String photo, ProductPo productPo, String fileTypeCd) {

        FileDto fileDto = new FileDto();
        fileDto.setCommunityId("-1");
        fileDto.setContext(photo);
        fileDto.setFileId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_file_id));
        fileDto.setFileName(fileDto.getFileId());

        fileDto.setSuffix("jpeg");
        String fileName = fileInnerServiceSMOImpl.saveFile(fileDto);

        FileRelPo fileRelPo = new FileRelPo();
        fileRelPo.setObjId(productPo.getProductId());
        fileRelPo.setRelTypeCd(fileTypeCd);
        fileRelPo.setFileRelId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_relId));
        fileRelPo.setFileRealName(fileName);
        fileRelPo.setFileSaveName(fileName);
        fileRelPo.setSaveWay(FileRelDto.SAVE_WAY_FTP);
        int save = fileRelInnerServiceSMOImpl.saveFileRel(fileRelPo);

        if (save < 1) {
            throw new IllegalArgumentException("保存文件失败");
        }
    }

}
